#include"mandate.h"

int ls(MYSQL *mysql,char *path,int *id,char * namelist)
{
    if(path[0]!='\0')
    {
        int original_id=*id;
        cd(mysql,path,id,namelist);
        *id=original_id;
        return 0;
    }
    char sql[100]={0};
    sprintf(sql,"select filename from file_tbl where pre_id=%d and is_delete=0;",*id);
    int qret =mysql_query(mysql,sql);
    if(qret!=0)
    {
        fprintf(stderr,"SQL statement error :%s\n",mysql_error(mysql));
    }

    MYSQL_RES *res=mysql_store_result(mysql);
    MYSQL_ROW row;

    char buf[100]={0};
    while((row=mysql_fetch_row(res))!=NULL)
    {
        bzero(buf,sizeof(buf));
        sprintf(buf,"|___%s\n",row[0]);
        strcat(namelist,buf);
    }
    return 0;
}

int tree(MYSQL *mysql,int *id,char *namelist,int flag)
{
    char sql[1024]={0};
    sprintf(sql,"select id,filename from file_tbl where pre_id=%d and is_delete=0;",*id);

    char *tree_msg[100];
    bzero(tree_msg,sizeof(tree_msg));
    int tree_id[100]={0};
    bzero(tree_id,sizeof(tree_id));
    int qret =mysql_query(mysql,sql);
    if(qret!=0)
    {
        fprintf(stderr,"SQL statement error :%s\n",mysql_error(mysql));
    }

    MYSQL_RES *res=mysql_store_result(mysql);
    MYSQL_ROW row;

    char buf[1024]={0};
    int i=0;
    while((row=mysql_fetch_row(res))!=NULL)
    {
        bzero(buf,sizeof(buf));
        tree_msg[i]=row[1];
        tree_id[i]=atoi(row[0]);
        for(int j=0;j<flag;j++)
        {
            strcat(buf,"|\t");
        }
        char temp[100]={0};
        sprintf(temp,"|_____%s\n",tree_msg[i]);
        strcat(buf,temp);
        strcat(namelist,buf);
        tree(mysql,&tree_id[i],namelist,flag+1);
        i++;
    }

    return 0;
}


